package xcmg.device.infra;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.UUID;
import org.springframework.web.multipart.MultipartHttpServletRequest;


@Slf4j
public class FileUtil {

    public static String uploadFile(MultipartFile file, String fileFolderPath, String fileName) throws Exception {
        if (file.isEmpty()) {
            throw new Exception("文件未上传");
        }

        if (fileName == null || "".equals(fileName.trim())) {
            // 截取文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            // 文件重命名
            fileName = UUID.randomUUID().toString() + "." + suffix;
        }
        Calendar now = Calendar.getInstance();
        //String dateStr = String.valueOf(now.get(Calendar.YEAR+(Calendar.MONTH+1)+Calendar.DAY_OF_MONTH));
        StringBuilder sb = new StringBuilder();
        sb.append(fileName);
        // 返回路径
        String path = sb.toString();

        try {
            File dirPath = new File(fileFolderPath);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(dirPath + "/" + fileName);
            if (!uploadFile.getParentFile().exists()) {
                uploadFile.getParentFile().mkdirs();
            }
            FileCopyUtils.copy(file.getBytes(), uploadFile);
        } catch (IOException e) {
            throw new Exception(e);
        }

        return path;
    }

    public static void downLoadFile(HttpServletResponse response, String filePath, String fileName) throws Exception {
        String downloadFilename = fileName;
        downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");

        File file = new File(filePath + fileName);
        if (file.exists()) {
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
            response.setContentType("application/octet-stream");
            BufferedInputStream bufferedInputStream = null;
            OutputStream outputStream = null;
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
                bufferedInputStream = new BufferedInputStream(fileInputStream);
                byte[] b = new byte[bufferedInputStream.available()];
                bufferedInputStream.read(b);
                outputStream = response.getOutputStream();
                outputStream.write(b);
            } catch (Exception e) {
                log.error("文件下载失败", e);
                throw new Exception(e);
            } finally {
                if (null != outputStream) {
                    bufferedInputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
                if (null != bufferedInputStream) {
                    bufferedInputStream.close();
                }
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            }


        }
    }

    public static void downLoadFileUseOldName(HttpServletResponse response, String filePath, String fileName,String oldName) throws Exception {
        File file = new File(filePath + fileName);
        oldName = URLEncoder.encode(oldName, "utf-8");
        if (file.exists()) {
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + oldName);
            response.setContentType("application/octet-stream");
            BufferedInputStream bufferedInputStream = null;
            OutputStream outputStream = null;
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
                bufferedInputStream = new BufferedInputStream(fileInputStream);
                byte[] b = new byte[bufferedInputStream.available()];
                bufferedInputStream.read(b);
                outputStream = response.getOutputStream();
                outputStream.write(b);
            } catch (Exception e) {
                throw new Exception(e);
            } finally {
                if (null != outputStream) {
                    bufferedInputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
                if (null != bufferedInputStream) {
                    bufferedInputStream.close();
                }
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            }


        }
    }

    /**
     * 删除文件。如果目标不存在或者目标不是文件，则直接返回true
     *
     * @param filePath
     * @param fileName
     * @return
     */
    public static boolean deleteFile(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        if (!file.exists() || !file.isFile()) {
            return true;
        }
        return file.delete();
//        return file.exists() && file.isFile() && file.delete();
    }

    /**
     *从request中取出要上传的多个文件
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static List<MultipartFile> analysisMultFilesByRequest(HttpServletRequest request) {
        List<MultipartFile> files = new ArrayList<>();
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            MultipartFile file = multiRequest.getFile(iter.next());
            if (null != file) {
                files.add(file);
            }
        }
        return files;
    }
}